package cn.wjx.taobaounion.presenter.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wjx.taobaounion.model.Api;
import cn.wjx.taobaounion.model.domain.CategoryContent;
import cn.wjx.taobaounion.presenter.ICategoryPagerPresenter;
import cn.wjx.taobaounion.utils.LogUtils;
import cn.wjx.taobaounion.utils.RetrofitManager;
import cn.wjx.taobaounion.view.ICategoryPagerCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static java.net.HttpURLConnection.HTTP_OK;

/**
 * @author WuChangJian
 * @date 2020/6/19 8:10
 */
public class CategoryPagerPresenterImpl implements ICategoryPagerPresenter {

    private static final int DEFAULT_PAGE = 1;
    private static CategoryPagerPresenterImpl sInstance = null;
    private Map<Integer, Integer> pagesInfo = new HashMap<>(); // 以categoryId-pageNo保存每个tab的信息

    @Override
    public void getContentByCategoryId(int categoryId) {
        for (ICategoryPagerCallback callback : mCategoryPagerCallbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoading();
            }
        }
        Call<CategoryContent> call = createTask(categoryId);
        call.enqueue(new Callback<CategoryContent>() {
            @Override
            public void onResponse(Call<CategoryContent> call, Response<CategoryContent> response) {
                int code = response.code();
                if (code == HTTP_OK) {
                    CategoryContent categoryContent = response.body();
                    LogUtils.d(CategoryPagerPresenterImpl.this, "categoryContent-->" + categoryContent);
                    // 通知UI更新
                    handleCategoryContentResult(categoryContent, categoryId);
                } else {
                    handleNetworkError(categoryId);
                    LogUtils.e(CategoryPagerPresenterImpl.this, "请求失败-->");
                }
            }

            @Override
            public void onFailure(Call<CategoryContent> call, Throwable t) {
                handleNetworkError(categoryId);
                LogUtils.e(CategoryPagerPresenterImpl.this, "onFailure-->" + t.toString());
            }
        });


    }

    private Call<CategoryContent> createTask(int categoryId) {
        Integer targetPage = pagesInfo.get(categoryId);
        if (targetPage == null) {
            targetPage = DEFAULT_PAGE;
            // 分页查询的页码 初始默认都是第一页
            pagesInfo.put(categoryId, targetPage);
        }
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        return api.getCategoryContent(categoryId, targetPage);
    }

    private void handleNetworkError(int categoryId) {
        for (ICategoryPagerCallback callback : mCategoryPagerCallbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onError();
            }
        }
    }

    private void handleCategoryContentResult(CategoryContent categoryContent, int categoryId) {
        if (categoryContent == null || categoryContent.getData().size() == 0) {
            for (ICategoryPagerCallback callback : mCategoryPagerCallbacks) {
                if (callback.getCategoryId() == categoryId) {
                    callback.onEmpty();
                }
            }
        } else {
            List<CategoryContent.DataBean> data = categoryContent.getData();
            for (ICategoryPagerCallback callback : mCategoryPagerCallbacks) {
                if (callback.getCategoryId() == categoryId) {
                    List<CategoryContent.DataBean> looperData = data.subList(data.size() - 5, data.size());
                    callback.onLooperListLoaded(looperData);
                    callback.onContentLoaded(data);
                }
            }
        }
    }

    @Override
    public void loaderMore(int categoryId) {
        // 加载更多
        // 1. 根据categoryId获取当前页面
        // 2. 页码++
        // 3. 请求数据
        // 4. 结果处理
        // 5. 更新UI
        Integer currentPage = pagesInfo.get(categoryId);
        if (currentPage == null) {
            currentPage = DEFAULT_PAGE;
        }
        currentPage += 1;
        pagesInfo.put(categoryId, currentPage);
        Call<CategoryContent> call = createTask(categoryId);
        call.enqueue(new Callback<CategoryContent>() {
            @Override
            public void onResponse(Call<CategoryContent> call, Response<CategoryContent> response) {
                if (response.code() == HTTP_OK) {
                    CategoryContent categoryContent = response.body();
                    handleLoaderMoreResult(categoryContent, categoryId);
                } else {
                    LogUtils.d(CategoryPagerPresenterImpl.this, "response code -->" + response.code());
                    handleLoaderMoreError(categoryId);
                }

            }
            @Override
            public void onFailure(Call<CategoryContent> call, Throwable t) {
                LogUtils.d(CategoryPagerPresenterImpl.this, "onFailure -- >" + t.getMessage());
                handleLoaderMoreError(categoryId);
            }
        });
    }

    private void handleLoaderMoreResult(CategoryContent categoryContent, int categoryId) {
        if (categoryContent == null || categoryContent.getData().size() == 0) {
            for (ICategoryPagerCallback callback : mCategoryPagerCallbacks) {
                if (callback.getCategoryId() == categoryId) {
                    callback.onLoaderMoreEmpty();
                }
            }
        } else {
            // notice callback to update ui
            for (ICategoryPagerCallback categoryPagerCallback : mCategoryPagerCallbacks) {
                if (categoryPagerCallback.getCategoryId() == categoryId) {
                    categoryPagerCallback.onLoaderMoreLoaded(categoryContent.getData());
                }
            }
        }
    }

    private void handleLoaderMoreError(int categoryId) {
        // 页码回退
        Integer currentPage = pagesInfo.get(categoryId);
        pagesInfo.put(categoryId, currentPage);
        for (ICategoryPagerCallback categoryPagerCallback : mCategoryPagerCallbacks) {
            if (categoryId == categoryPagerCallback.getCategoryId()) {
                categoryPagerCallback.onLoaderMoreError();
            }
        }
    }

    @Override
    public void reload(int categoryId) {

    }

    // 首页有多个tab，每个tab对应一个fragment由viewpager所创建，用一个Presenter实现管理多个PagerFragment,
    // 需要集合保存每个fragment的必要信息
    private List<ICategoryPagerCallback> mCategoryPagerCallbacks = new ArrayList<>();
    @Override
    public void registerViewCallback(ICategoryPagerCallback callback) {
        if (!mCategoryPagerCallbacks.contains(callback)) {
            mCategoryPagerCallbacks.add(callback);
        }
    }

    @Override
    public void unregisterViewCallback(ICategoryPagerCallback callback) {
        if (mCategoryPagerCallbacks.contains(callback)) {
            mCategoryPagerCallbacks.remove(callback);
        }
    }
}
